//获取左侧菜单
import { MyAppType } from "@/router/type";

// / import.meta.glob() 直接引入所有的模块 Vite 独有的功能
const modules = import.meta.glob("../router/modules/**/*.tsx", {
  eager: true,
}) as {
  [key: string]: { default: MyAppType };
};

const routeModuleList: MyAppType[] = [];

// 加入到路由集合中
Object.keys(modules).forEach((key) => {
  const mod = modules[key]?.default || {};
  const modList = Array.isArray(mod) ? [...mod] : [mod];
  routeModuleList.push(...modList);
});

// 格式化菜单数据
const useMenu = (): MenuType[] => {
  let arr: MenuType[] = [];
  if (routeModuleList && routeModuleList.length > 0) {
    const menuList = routeModuleList
      .sort((a, b) => a.meta?.order - b.meta?.order)
      .map((item): MenuType => {
        const obj: MenuType = {
          key: item.path,
          title: item.meta?.title,
          icon: item.meta?.icon,
        };
        if (item.children && item.children.length > 0) {
          obj.children = item.children.map((child): any => {
            return {
              key: item.path + "/" + child.path,
              title: child.meta?.title,
              icon: child.meta?.icon,
              path: item.path + "/" + child.path,
            };
          });
        }
        return obj;
      });
    arr = menuList;
  }
  return arr;
};

export { useMenu };
